package com.xinlong.shop.api.order;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import com.xinlong.shop.api.common.BuyerBaseController;
import com.xinlong.shop.core.member.service.IMemberService;
import com.xinlong.shop.core.order.OrderQueryParam;
import com.xinlong.shop.core.order.OrderStatusEnum;
import com.xinlong.shop.core.order.entity.Order;
import com.xinlong.shop.core.order.entity.dto.CreateOrderDTO;
import com.xinlong.shop.core.order.entity.vo.OrderVO;
import com.xinlong.shop.core.order.service.IOrderService;
import com.xinlong.shop.framework.common.R;
import com.xinlong.shop.framework.core.entity.Member;
import com.xinlong.shop.framework.security.constant.SecurityConstants;
import com.xinlong.shop.framework.security.util.TokenUtil;
import com.xinlong.shop.framework.service.ISysSettingService;
import com.xinlong.shop.framework.weixin.service.WeiXinMpService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Sylow
 * @Description 买家订单API
 * @Date: Created in 15:13 2023/7/4
 */
@Api(tags = "买家订单API")
@Validated      // get请求验证参数时需要
@RestController
@RequestMapping("/buyer/order/order")
public class BuyerOrderController extends BuyerBaseController {

    private final IOrderService orderService;
    private final ISysSettingService sysSettingService;
    private final WeiXinMpService weiXinMpService;

    public BuyerOrderController(IOrderService orderService, IMemberService memberService, TokenUtil tokenUtil, ISysSettingService sysSettingService, WeiXinMpService weiXinMpService) {
        super(memberService, tokenUtil);
        this.orderService = orderService;
        this.sysSettingService = sysSettingService;
        this.weiXinMpService = weiXinMpService;
    }

    @ApiOperation(value = "创建订单")
    @ApiResponses(@ApiResponse(code = 200, message = "操作成功", response = Order.class))
    @RequestMapping(value = "/create-order", method = RequestMethod.POST, produces = "application/json")
    public R createOrder(String code, String openid, @RequestBody CreateOrderDTO createOrderDTO, @RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token){

        // 验证用户是否存在
        Member member = getMember(token);
        if (member == null) {
            return R.error("用户不存在");
        }

        createOrderDTO.setMemberId(member.getId());
        createOrderDTO.setMemberName(member.getMemberName());
        Order order = this.orderService.createOrder(createOrderDTO);
        Map<String,Object> settings = sysSettingService.getSetting();
        Map<String, Object> result = new HashMap<>();
        // 判断有没有开启支付
        boolean openWeixinPay = (boolean) settings.get("openWeixinPay");
        if (openWeixinPay) {
            if (StrUtil.isBlank(openid)) {
                openid = weiXinMpService.getOpenId(code);
                if (StrUtil.isBlank(openid)) {
                    return R.error("操作失败，请重试");
                }
            }
            PrepayWithRequestPaymentResponse response = weiXinMpService.pay(order.getOrderSn(), openid,
                    order.getOrderPrice(), "闲逛商城-订单：" + order.getOrderSn());

            result.put("openWeixinPay", openWeixinPay);
            result.put("response", response);
            result.put("openid", openid);   // 返回前端做缓存，暂时不保存到后端
        } else {
            result.put("openWeixinPay", openWeixinPay);
        }

        return R.success(result);
    }

    @ApiOperation(value = "订单列表")
    @ApiResponses(@ApiResponse(code = 200, message = "操作成功", response = OrderVO.class))
    @RequestMapping(value = "", method = RequestMethod.GET, produces = "application/json")
    public R orderList(Integer current, String status, @RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token) {
        Integer statusIndex = null;
        if ("paid_off".equals(status)) {
            statusIndex = OrderStatusEnum.PAID_OFF.getCode();
        } else if("shipped".equals(status)) {
            statusIndex = OrderStatusEnum.SHIPPED.getCode();
        } else if("complete".equals(status)) {
            statusIndex = OrderStatusEnum.COMPLETE.getCode();
        }
        Member member = getMember(token);
        OrderQueryParam orderQueryParam = new OrderQueryParam();
        orderQueryParam.setOrderStatus(statusIndex);
        orderQueryParam.setMemberId(member.getId());
        IPage<OrderVO> page = new Page<>(current, 10);
        page = this.orderService.selectPageOrderVo(page, orderQueryParam);
        return R.success("操作成功", page);
    }

}
